﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ds.U6;
using DaInterFace;
using DaInterFace.UMode;
using System.Threading;
using System.Drawing;
using System.Data;

namespace DaSub.UMode
{
    public class UModeHole : IUModeHole
    {
        DsU6 _u6;
        DeviceInfo _di = new DeviceInfo();
        MeterInfoObject _meterInfo;
        Boolean _isOpen = false;
        Boolean _isReading = false;
        Boolean _allowRepeat = false;
        String _ip;
        MatchStyle _style;
        String _item;
        String _portName;
        Boolean _forbidRepeat;
        IDataCenter _daCenter;
        String _iMessage;
        Font _font = new Font("宋体", 10.0f);
        int _failTimes = 0;
        Thread _mainThread;
        HMode _hmode;
        String _cameraIP = "";
        String _errorNum = "";

        public event IMessageHandler IMessageEvent;

        public String PortName { get { return _portName; } }
        public String ItemName { get { return _item; } }
        public MeterInfoObject MeterInfo { get { return _meterInfo; } }

        internal UModeHole(IDataCenter daCenter, String ip, MatchStyle style, String item, String portName, Boolean forbidRepeat, String cameraIP,String errorNum)
        {
            _ip = ip;
            _style = style;
            _item = item;
            _portName = portName;
            _daCenter = daCenter;
            _forbidRepeat = forbidRepeat;
            _u6 = new DsU6(_ip, 20108);
            _hmode = new HMode();
            _errorNum = errorNum;

            if (!cameraIP.Equals(""))
            {
                _cameraIP = cameraIP;
                _hmode.Add(cameraIP, Mode_ChangeChannel.No1);
            }

            _mainThread = new Thread(Start);
            _mainThread.IsBackground = true;
            _mainThread.Name = "执行线程";
            _mainThread.Start();
        }

        private void IMessage(MessageType type, String iMessage)
        {
            _iMessage = iMessage;
            if (IMessageEvent != null)
            {
                IMessageEvent.Invoke(type, iMessage);
            }
        }

        private void Start()
        {
            while (true)
            {
                try
                {
                    if (!_isOpen)
                    {
                        Connect();
                    }
                    else
                    {
                        Run();
                    }

                    if (_isOpen)
                    {
                        Thread.Sleep(300);
                    }
                    else
                    {
                        Thread.Sleep(3000);
                    }
                }
                catch (Exception) { }
            }
        }

        private void Connect()
        {
            try
            {
                IMessage(MessageType.Note, "正在连接...");
                _u6.Open();
                _isOpen = _u6.IsPortOpen;
                if (_isOpen && _u6.Settings_SetRelay(SwitchEnum.No1, 0) == DevResults.OK)
                {
                    _daCenter.DaUMode.Message(MessageType.Note, String.Format("料口[{0}]，连接IP[{1}]成功", _portName, _ip));
                    IMessage(MessageType.Note, _iMessage = "连接正常");
                }
                else
                {
                    IMessage(MessageType.Warning, "请检查U6跳线是否在1号线上。");
                }
            }
            catch (Exception ex)
            {
                IMessage(MessageType.Error, ex.Message);
            }
        }

        public void Dispose()
        {
            try
            {
                _mainThread.Abort();
                _mainThread = null;
                _u6.Close();
                _u6.Dispose();
            }
            catch (Exception)
            {

            }
        }

        private void Run()
        {
            if (_u6.Card_DeviceInfo(_di) == DevResults.OK)
            {
                if (_di.CardSerial == "" || _di.CardSerial == "00000000")
                {
                    if (_isReading)
                    {
                        _isReading = false;
                        _u6.Screen_ShowLogo();
                        Forbid();
                        if (_meterInfo != null)
                        {
                            switch (_meterInfo.Type)
                            {
                                case 0:
                                    _daCenter.DaUMode.Message(MessageType.Note, String.Format("销售-料口[{0}],编号[{1}],车辆[{2}],料种[{3}],磁卡拔出", _portName, _meterInfo.BillNumber, _meterInfo.CarNumber, _meterInfo.Item.Name));
                                    break;
                                case 3:
                                    _daCenter.DaUMode.Message(MessageType.Note, String.Format("调拨-料口[{0}],编号[{1}],车辆[{2}],料种[{3}],磁卡拔出", _portName, _meterInfo.BillNumber, _meterInfo.CarNumber, _meterInfo.Item.Name));
                                    break;
                            }

                            _meterInfo = null;
                        }
                    }
                    else if (_di.Relay1)
                    {
                        _u6.Switch_Close(SwitchEnum.No1);
                    }
                }
                else if (!_isReading)
                {
                    _isReading = true;
                    if (!_cameraIP.Equals(""))
                    {
                        _hmode.CaptureImage();
                        Thread.Sleep(500);
                    }
                    CheckInfo(_di.CardSerial);
                }
            }
            else
            {
                _failTimes++;
                if (_failTimes > 10)
                {
                    _isOpen = false;
                }
            }
        }

        public void Allow()
        {
            CardState cs = CardState.NoCard;
            _u6.Card_Write(16, "销售.已装料", out cs);
            _u6.Card_Write(18, _portName, out cs);
            _u6.Switch_Open(SwitchEnum.No1, 0);
            _u6.Screen_Print(3, 3, "正在放料", _font);
            IMessage(MessageType.Note, "正在放料");
        }

        public void Forbid()
        {
            _u6.Switch_Close(SwitchEnum.No1);
            _u6.Screen_Print(3, 3, "禁止放料", _font);
            IMessage(MessageType.Note, "禁止放料");
        }

        public Boolean CheckItem(String item, String holeItems)
        {
            String[] items = holeItems.Split('·');
            for (int i = 0; i < items.Length; i++)
            {
                if (items[i] == item)
                {
                    return true;
                }
            }

            return false;
        }

        private bool IsFitMatch(String CameraCar, String UnManualCar)
        {
            if (!_errorNum.Equals(""))
            {
                StringCompute stringcompute1 = new StringCompute();
                CameraCar = CameraCar.ToLower();
                UnManualCar = UnManualCar.ToLower();
                stringcompute1.SpeedyCompute(CameraCar, UnManualCar);    // 计算相似度， 不记录比较时间
                decimal rate = stringcompute1.ComputeResult.Rate;
                ErrorLog.SetLogMessage("手工录入车牌号：" + UnManualCar + ";  抓拍车牌号：" + CameraCar + ";  相似度:" + rate.ToString());
                if (Common.CDec(_errorNum) <= rate)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }

            return true;
        }

        private Boolean CheckInfo(String serial)
        {
            Boolean right = false;

            try
            {

                _u6.Light_Open();
                _meterInfo = _daCenter.DaData.GetMeterInfoByCardSerial(serial);
                if (_meterInfo.InfoEnable)
                {
                    //检验是否存在本地,允许放料

                    if (_meterInfo.Type==5)
                    {
                        right = true;
                        _u6.Screen_ClearAll();
                        _u6.Screen_Print(0, 0, "管理卡-" + serial, _font);
                        _daCenter.DaUMode.Message(MessageType.Note, String.Format("管理卡-[{0}]，销售-料口[{1}],物料-[{2}],正在放料",serial, _portName, _item));
                        Allow();
                        return right;
                    }

                    //不存在本地，检车车辆
                    if (!_cameraIP.Equals(""))
                    {
                        Thread.Sleep(200);
                        if (_hmode.info != null)
                        {

                            if (!IsFitMatch(_hmode.info.CarNo.Replace("\0", ""), _meterInfo.CarNumber))
                            {
                                _u6.Screen_ClearAll();
                                _u6.Screen_Print(0, 0, _meterInfo.CarNumber, _font);
                                _u6.Screen_Print(0, 1, _hmode.info.CarNo.Replace("\0", ""), _font);
                                _u6.Screen_Print(0, 2, "车牌不匹配", _font);
                                return false;
                            }
                        }
                    }

                    if (_meterInfo.Type == 0) //销售磁卡
                    {
                        _u6.Screen_ClearAll();
                        if (_forbidRepeat && _meterInfo.EmpChk != "" && _allowRepeat == false)
                        {
                            _u6.Screen_Print(0, 2, "不能重复刷卡", _font);
                            Forbid();
                            right = false;
                            return right;
                        }
                        if (_meterInfo.Step == 2)
                        {
                            switch (_style)
                            {
                                case MatchStyle.MatchName:
                                    if (CheckItem(_meterInfo.Item.Name, _item))
                                    {
                                        right = true;
                                        _daCenter.DaUMode.Message(MessageType.Note, String.Format("销售-料口[{0}],编号[{1}],车辆[{2}],料种[{3}],正在放料", _portName, _meterInfo.BillNumber, _meterInfo.CarNumber, _meterInfo.Item.Name));
                                        Allow();
                                    }
                                    else
                                    {
                                        _daCenter.DaUMode.Message(MessageType.Note, String.Format("销售-料口[{0}],编号[{1}],车辆[{2}],料种[{3}],禁止放料", _portName, _meterInfo.BillNumber, _meterInfo.CarNumber, _meterInfo.Item.Name));
                                        Forbid();
                                    }
                                    break;
                                case MatchStyle.MatchNumber:
                                    if (CheckItem(_meterInfo.Item.Number, _item))
                                    {
                                        right = true;
                                        _daCenter.DaUMode.Message(MessageType.Note, String.Format("销售-料口[{0}],编号[{1}],车辆[{2}],料种[{3}],正在放料", _portName, _meterInfo.BillNumber, _meterInfo.CarNumber, _meterInfo.Item.Name));
                                        Allow();
                                    }
                                    else
                                    {
                                        _daCenter.DaUMode.Message(MessageType.Note, String.Format("销售-料口[{0}],编号[{1}],车辆[{2}],料种[{3}],禁止放料", _portName, _meterInfo.BillNumber, _meterInfo.CarNumber, _meterInfo.Item.Name));
                                        Forbid();
                                    }
                                    break;
                                case MatchStyle.MatchPrice:
                                    Decimal price1 = 0;
                                    Decimal price2 = 0;
                                    price1 = _meterInfo.ItemPrice;
                                    Decimal.TryParse(_item, out price2);
                                    if (price1 <= price2)
                                    {
                                        right = true;
                                        _daCenter.DaUMode.Message(MessageType.Note, String.Format("销售-料口[{0}],编号[{1}],车辆[{2}],料种[{3}],正在放料", _portName, _meterInfo.BillNumber, _meterInfo.CarNumber, _meterInfo.Item.Name));
                                        Allow();
                                    }
                                    else
                                    {
                                        _daCenter.DaUMode.Message(MessageType.Note, String.Format("销售-料口[{0}],编号[{1}],车辆[{2}],料种[{3}],禁止放料", _portName, _meterInfo.BillNumber, _meterInfo.CarNumber, _meterInfo.Item.Name));
                                        Forbid();
                                    }
                                    break;
                                case MatchStyle.MatchItem:
                                    if (_meterInfo.SourceItem.Name == _item)
                                    {
                                        right = true;
                                        _daCenter.DaUMode.Message(MessageType.Note, String.Format("销售-料口[{0}],编号[{1}],车辆[{2}],料种[{3}],正在放料", _portName, _meterInfo.BillNumber, _meterInfo.CarNumber, _meterInfo.Item.Name));
                                        Allow();
                                    }
                                    else
                                    {
                                        _daCenter.DaUMode.Message(MessageType.Note, String.Format("销售-料口[{0}],编号[{1}],车辆[{2}],料种[{3}],禁止放料", _portName, _meterInfo.BillNumber, _meterInfo.CarNumber, _meterInfo.Item.Name));
                                        Forbid();
                                    }
                                    break;

                            }

                            if (right)
                            {
                                _daCenter.DaData.ExeProcedure(_meterInfo.Base.Number, String.Format("UPDATE KEW_SalesInfo SET FText9='{0}' WHERE FID={1}", _portName, _meterInfo.BillID));

                            }
                        }
                        else
                        {
                            //没计量皮重
                            _daCenter.DaUMode.Message(MessageType.Warning, String.Format("车辆：{0} 该状态不能装料", _meterInfo.CarNumber));
                            _u6.Screen_Print(0, 2, "没有皮重", _font);
                        }

                        _allowRepeat = false;
                        _u6.Screen_Print(0, 0, "车牌:" + _meterInfo.CarNumber, _font);
                        _u6.Screen_Print(0, 1, _meterInfo.Item.Name, _font);
                    }
                    else if (_meterInfo.Type == 1) //采购磁卡
                    {
                        _u6.Screen_ClearAll();
                        if (_forbidRepeat && _meterInfo.EmpChk != "" && _allowRepeat == false)
                        {
                            _u6.Screen_Print(0, 2, "不能重复刷卡", _font);
                            Forbid();
                            right = false;
                            return right;
                        }
                        if (_meterInfo.Step == 2)
                        {
                            switch (_style)
                            {
                                case MatchStyle.MatchName:
                                    if (CheckItem(_meterInfo.Item.Name, _item))
                                    {
                                        right = true;
                                        _daCenter.DaUMode.Message(MessageType.Note, String.Format("采购-料口[{0}],编号[{1}],车辆[{2}],料种[{3}],正在卸料", _portName, _meterInfo.BillNumber, _meterInfo.CarNumber, _meterInfo.Item.Name));
                                        Allow();
                                    }
                                    else
                                    {
                                        _daCenter.DaUMode.Message(MessageType.Note, String.Format("采购-料口[{0}],编号[{1}],车辆[{2}],料种[{3}],禁止卸料", _portName, _meterInfo.BillNumber, _meterInfo.CarNumber, _meterInfo.Item.Name));
                                        Forbid();
                                    }
                                    break;
                                case MatchStyle.MatchNumber:
                                    if (CheckItem(_meterInfo.Item.Number, _item))
                                    {
                                        right = true;
                                        _daCenter.DaUMode.Message(MessageType.Note, String.Format("采购-料口[{0}],编号[{1}],车辆[{2}],料种[{3}],正在卸料", _portName, _meterInfo.BillNumber, _meterInfo.CarNumber, _meterInfo.Item.Name));
                                        Allow();
                                    }
                                    else
                                    {
                                        _daCenter.DaUMode.Message(MessageType.Note, String.Format("采购-料口[{0}],编号[{1}],车辆[{2}],料种[{3}],禁止卸料", _portName, _meterInfo.BillNumber, _meterInfo.CarNumber, _meterInfo.Item.Name));
                                        Forbid();
                                    }
                                    break;
                                case MatchStyle.MatchPrice:
                                    Decimal price1 = 0;
                                    Decimal price2 = 0;
                                    price1 = _meterInfo.ItemPrice;
                                    Decimal.TryParse(_item, out price2);
                                    if (price1 <= price2)
                                    {
                                        right = true;
                                        _daCenter.DaUMode.Message(MessageType.Note, String.Format("采购-料口[{0}],编号[{1}],车辆[{2}],料种[{3}],正在卸料", _portName, _meterInfo.BillNumber, _meterInfo.CarNumber, _meterInfo.Item.Name));
                                        Allow();
                                    }
                                    else
                                    {
                                        _daCenter.DaUMode.Message(MessageType.Note, String.Format("采购-料口[{0}],编号[{1}],车辆[{2}],料种[{3}],禁止卸料", _portName, _meterInfo.BillNumber, _meterInfo.CarNumber, _meterInfo.Item.Name));
                                        Forbid();
                                    }
                                    break;
                                case MatchStyle.MatchItem:
                                    if (_meterInfo.SourceItem.Name == _item)
                                    {
                                        right = true;
                                        _daCenter.DaUMode.Message(MessageType.Note, String.Format("采购-料口[{0}],编号[{1}],车辆[{2}],料种[{3}],正在卸料", _portName, _meterInfo.BillNumber, _meterInfo.CarNumber, _meterInfo.Item.Name));
                                        Allow();
                                    }
                                    else
                                    {
                                        _daCenter.DaUMode.Message(MessageType.Note, String.Format("采购-料口[{0}],编号[{1}],车辆[{2}],料种[{3}],禁止卸料", _portName, _meterInfo.BillNumber, _meterInfo.CarNumber, _meterInfo.Item.Name));
                                        Forbid();
                                    }
                                    break;

                            }

                            if (right)
                            {
                                _daCenter.DaData.ExeProcedure(_meterInfo.Base.Number, String.Format("UPDATE KEW_PurchInfo SET FText9='{0}' WHERE FID={1}", _portName, _meterInfo.BillID));
                            }
                        }
                        else
                        {
                            //没计量皮重
                            _daCenter.DaUMode.Message(MessageType.Warning, String.Format("车辆：{0} 该状态不能卸料", _meterInfo.CarNumber));
                            _u6.Screen_Print(0, 2, "没有毛重", _font);
                        }

                        _allowRepeat = false;
                        _u6.Screen_Print(0, 0, "车牌:" + _meterInfo.CarNumber, _font);
                        _u6.Screen_Print(0, 1, _meterInfo.Item.Name, _font);
                    }
                    else if (_meterInfo.Type == 3)
                    {
                        _u6.Screen_ClearAll();
                        _u6.Screen_Print(0, 0, "调拨", _font);
                        _u6.Screen_Print(0, 1, _meterInfo.Item.Name, _font);
                        switch (_style)
                        {
                            case MatchStyle.MatchName:
                                if (CheckItem(_meterInfo.Item.Name, _item))
                                {
                                    right = true;
                                    _daCenter.DaUMode.Message(MessageType.Note, String.Format("调拨-料口[{0}],编号[{1}],车辆[{2}],料种[{3}],正在放料", _portName, _meterInfo.BillNumber, _meterInfo.CarNumber, _meterInfo.Item.Name));
                                    Allow();
                                }
                                else
                                {
                                    _daCenter.DaUMode.Message(MessageType.Note, String.Format("调拨-料口[{0}],编号[{1}],车辆[{2}],料种[{3}],禁止放料", _portName, _meterInfo.BillNumber, _meterInfo.CarNumber, _meterInfo.Item.Name));
                                    Forbid();
                                }
                                break;
                            case MatchStyle.MatchNumber:
                                if (CheckItem(_meterInfo.Item.Number, _item))
                                {
                                    right = true;
                                    _daCenter.DaUMode.Message(MessageType.Note, String.Format("调拨-料口[{0}],编号[{1}],车辆[{2}],料种[{3}],正在放料", _portName, _meterInfo.BillNumber, _meterInfo.CarNumber, _meterInfo.Item.Name));
                                    Allow();
                                }
                                else
                                {
                                    _daCenter.DaUMode.Message(MessageType.Note, String.Format("调拨-料口[{0}],编号[{1}],车辆[{2}],料种[{3}],禁止放料", _portName, _meterInfo.BillNumber, _meterInfo.CarNumber, _meterInfo.Item.Name));
                                    Forbid();
                                }
                                break;
                            case MatchStyle.MatchPrice:
                                right = true;
                                _daCenter.DaUMode.Message(MessageType.Note, String.Format("调拨-料口[{0}],编号[{1}],车辆[{2}],料种[{3}],正在放料", _portName, _meterInfo.BillNumber, _meterInfo.CarNumber, _meterInfo.Item.Name));
                                Allow();
                                break;
                        }
                        _u6.Screen_Print(0, 0, "车牌:" + _meterInfo.CarNumber, _font);
                        _u6.Screen_Print(0, 1, _meterInfo.Item.Name, _font);
                    }
                    else if (_meterInfo.Type == 4)
                    {
                        _allowRepeat = true;
                        _u6.Screen_Print(0, 2, "已重置", _font);
                    }
                    else
                    {
                        //不是销售磁卡
                        _daCenter.DaUMode.Message(MessageType.Note, String.Format("料口:{0},不是销售或者调拨磁卡", _portName));
                        _u6.Screen_Print(0, 2, "非销售、调拨磁卡", _font);
                    }



                }
                else
                {
                    _daCenter.DaUMode.Message(MessageType.Note, String.Format("料口:{0},数据加载异常:{1}", _portName, _meterInfo.UnEnableReason));
                    _u6.Screen_Print(0, 2, "数据加载异常", _font);
                }
            }
            catch (Exception ex)
            {
                ErrorLog.WriteLog(ex);
                _daCenter.DaUMode.Message(MessageType.Note, String.Format("料口:{0},{1}", _portName, ex.Message));
                _u6.Screen_Print(0, 2, "系统异常", _font);
            }

            return right;
        }


    }
}
